package main

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/cmd/fyne_settings/settings"
	"fyne.io/fyne/v2/theme"
	"net/url"
)

var topWindow fyne.Window

func shortcutFocused(s fyne.Shortcut, w fyne.Window)  {
	if focused, ok := w.Canvas().Focused().(fyne.Shortcutable); ok {
		// Shortcutable describes any CanvasObject that can respond to shortcut commands (quit, cut, copy, and paste).
		focused.TypedShortcut(s)
	}
}

func main() {
	// 创建应用
	a := app.NewWithID("fyne.gui.demo")
	// 设置应用图标
	a.SetIcon(theme.FyneLogo())

	w := a.NewWindow("Fyne widget")
	// 记录最上层的window
	topWindow = w

	newItem := fyne.NewMenuItem("New", nil)
	otherItem := fyne.NewMenuItem("Other", nil)
	// 下拉框增加item
	otherItem.ChildMenu = fyne.NewMenu("",
		fyne.NewMenuItem("Project", func() {
			fmt.Println("Menu new ->other->project")
		}),
		fyne.NewMenuItem("Mail", func() {
			fmt.Println("Menu New ->Other->Mail")
		}),
	)
	newItem.ChildMenu = fyne.NewMenu("new child item",
		fyne.NewMenuItem("File", func() {
			fmt.Println("Menu New->File")
		}),
		fyne.NewMenuItem("Directory", func() {

		}),
	)

	settingsItem := fyne.NewMenuItem("Settings", func() {
		w := a.NewWindow("Fyne Settings")
		// creates a new settings screen to handle appearance configuration
		w.SetContent(settings.NewSettings().LoadAppearanceScreen(w))
		w.Resize(fyne.NewSize(480, 480))
		// Show the window on screen.
		w.Show()
	})

	cutItem := fyne.NewMenuItem("Cut", func() {
		// 该窗口支持剪贴赋值
		shortcutFocused(&fyne.ShortcutCut{Clipboard: w.Clipboard()}, w)
	})

	copyItem := fyne.NewMenuItem("Copy", func() {
		// 该窗口支持剪贴赋值
		shortcutFocused(&fyne.ShortcutCopy{Clipboard: w.Clipboard()}, w)
	})

	pasteItem := fyne.NewMenuItem("Paste", func() {
		// 该窗口支持剪贴赋值
		shortcutFocused(&fyne.ShortcutPaste{Clipboard: w.Clipboard()}, w)
	})

	findItem := fyne.NewMenuItem("Find", func() {
		fmt.Println("Menu Find")
	})

	helpMenu := fyne.NewMenu("Help",
		fyne.NewMenuItem("Doc", func() {
			u, _ := url.Parse("www.baidu.com")
			_ = a.OpenURL(u)
		}),
		// 增加一个分割符号
		fyne.NewMenuItemSeparator(),
		fyne.NewMenuItem("Git Store", func() {
			u, _ := url.Parse("www.github.com")
			//Open a URL in the default browser application.
			_ = a.OpenURL(u)
		}),
	)

	file := fyne.NewMenu("File", newItem)
	if !fyne.CurrentDevice().IsMobile() {
		file.Items = append(file.Items, fyne.NewMenuItemSeparator(), otherItem, settingsItem)
	}

	mainMenu := fyne.NewMainMenu(
		file,
		fyne.NewMenu("Edit", cutItem, copyItem, pasteItem, fyne.NewMenuItemSeparator(), findItem),
		helpMenu)
	//adds a top level menu to this window.
	w.SetMainMenu(mainMenu)
	//indicates that closing this window should exit the app
	// 窗口关闭整个APP也进行关闭
	w.SetMaster()

	w.Resize(fyne.NewSize(640, 460))
	w.ShowAndRun()
}
